/**
 * @file 创建服务器的方法
 */
import { createServer } from "http"
import { AppObject, MiddlewareFunction, AppOptions } from "../../index.d.js"
import { defineRouter } from "./router.js"
import { combineMiddleware } from "./middleware.js"
import { errorMiddleware, requestLocationMiddleware, requestQueryMiddleware, responseHeaderMiddleware, requestHandlerMiddleware } from "#middleware"

const defaultOptions: AppOptions = {
  routes: [],
  strict: false,
  serveOptions: {}
}
/** 创建服务器应用
 * @param appOptions 可选 创建服务器配置
 * @returns AppObject 对象
 */
export function createApp(appOptions: AppOptions = {}): AppObject {
  const { routes = [], strict = false, serveOptions = {}, readDirname = "" } = { ...defaultOptions, ...appOptions }
  // 解析路径, 输出路径配置的键值对对象
  const router = defineRouter(routes)

  // 中间件列表
  const middlewareList: MiddlewareFunction[] = [
    errorMiddleware, // 错误拦截
    requestLocationMiddleware, // 请求路径解析 注入 requestLocation
    requestQueryMiddleware, // 请求参数解析 注入 requestQuery
    responseHeaderMiddleware, // 根据路径自动配置 response 的请求头
    requestHandlerMiddleware // 执行请求对相应的方式执行接口或读取文件
  ]

  const server = createServer(serveOptions)

  server.on(
    "request",
    combineMiddleware(middlewareList, {
      server, // 服务器对象
      router, // router 配置
      strict, // 是否严格匹配
      readDirname // 用于读取文件的目录
    })
  )

  const app: AppObject = {
    server,
    use(middleware) {
      middlewareList.push(middleware)
      return app
    },
    listen(listenOptions, listener) {
      server.listen(listenOptions, () => {
        listener(server)
      })
    }
  }

  return app
}
